# _*_ coding:utf-8 _*_

__all__ = ['register_rule', 'get_rule']

import re
import StrUtils
import ImportCode
import CommonUtils

logger = CommonUtils.getLogger('RuleTemplate')

g_rules = {}

'''
规则Rule就是一组条件、动作集合，它们合起来完成一些数据的判断
if expr:  action

Rule可以自己声明global变量的方式，实现互相之间的数据共享，一条规则只能是一行的，如想写多个语句，语句间用分号
保留的关键字：
    $plan，准备动作
    $final，清理动作
    $comment, 注释，HTML表格中的表头
    $dataid，数据ID，构成Pandas Dataframe中的index或column
'''

rule_sample = {
    '$comment' : '汉族',
    '$dataid'  : 'nation_01',
    '$plan' : 'import numpy as np',
    'name[0:2]' : '"Sun"//Sun',
    'nation': ['"01"//汉族'],     # 汉族
    '$final' : ''
}

def switch_rule(x):
    try:
        return g_rules[x]
    except KeyError:
        return ''


def get_rule(_src, strExpr):
    #
    # strExpr增例： $rule_1 rule_expr, rule_id
    #
    label = re.match(r'^\$\w+', strExpr, re.I)
    if label is None:
        return ('',)*5
    pos = label.span()[1]
    rule = label[0]

    t = switch_rule(rule)
    if t:
        valExpr = strExpr[pos:]

        # RuleTemplate中的设置为最低优先级，稍高优先级为环境参数，最高优先级为角本中的语法
        dictExpr = CommonUtils.getDict('argd', t , {})
        if _src.parameters:
            dictExpr.update(_src.parameters)
        if (valExpr[0] == '{'):
            dict_ = eval(valExpr)
            valExpr = CommonUtils.getDict('_p__', dict_ , '')
            if valExpr == '':
                valExpr = strExpr[pos:]
            else:
                dictExpr.update(dict_)

        rule_ = {}
        plan = ''
        final = ''
        comment = ''
        dataid = ''
        # format every element
        for key, value in t.items():
            if (key == '$plan'):
                plan += value
            elif (key == '$final'):
                final += value
            elif (key == '$comment'):
                comment += value
            elif (key == '$dataid'):
                dataid += value
            else:
                key_ = key.format(valExpr=valExpr, **dictExpr)
                if isinstance(value, str):
                    value_ = value.format(valExpr=valExpr, **dictExpr)
                    rule_[key_] = [value_]
                else:
                    rule_[key_] = value
        return plan, rule_, final, comment, dataid
    else:
        return ('',)*5


def register_rule(name, rule):
    temp = {}
    for key, value in rule.items():
        if isinstance(key, str):
            key = key.strip()
        if isinstance(value, str):
            value = value.strip()

        if (key[0] != '$'):
            status, key = StrUtils.getStatementContent(key)
            status, s = ImportCode.sr_CheckCode(None, key)
            if status:
                return s

            status, value = StrUtils.getStatementContent(value)
            status, s = ImportCode.sr_CheckCode(None, value)
            if status:
                return s

        temp[key] = value
    g_rules[name] = temp
    return ''


retStr = register_rule('$rule_sample', rule_sample)
if (retStr != ''):
    logger.error('FAIL: register_rule("$rule_sample"), ' + retStr)


if __name__ == '__main__':
    str0 = register_rule('$rule_sample', rule_sample)
    print (str0)

    print ("switch_rule('$rule_sample')")
    print (switch_rule('$rule_sample'))
    print ("\nget_rule('$rule_sample 1 expr')")
    print (get_rule('$rule_sample 1 expr'))
